package com.mldong.validation.unique;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mldong.holder.RequestParamIdHolder;
import com.mldong.holder.ValidatorGroupHolder;
import com.mldong.validation.Groups;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 唯一性校验逻辑
 * @author mldong
 * @date 2022-10-23
 */
public class TableUniqueValidatorClass  implements ConstraintValidator<TableUniqueValidator,Object> {
    private Class<? extends BaseMapper> mapperClass;
    private String columnName;
    @Override
    public void initialize(TableUniqueValidator tableUniqueValidator) {
        this.mapperClass = tableUniqueValidator.mapperClass();
        this.columnName = tableUniqueValidator.columnName();
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        // 1. 获取tableName/columnName的值
        // 2. 获取是否为更新@Validated({Groups.Update.class}==>isUpdate
        // 3. 如果是更新，需要获取当前记录主键值==>param.id
        // 4. 动态构建查询条件
        Class<?> groupClass = ValidatorGroupHolder.get();
        boolean isUpdate = Groups.Update.class.equals(groupClass);
        String id = RequestParamIdHolder.get();
        return check(o, id,isUpdate);
    }

    /**
     * 校验
     * @param columnValue
     * @param id
     * @param isUpdate
     * @return
     */
    private boolean check(Object columnValue, String id,boolean isUpdate) {
        QueryWrapper queryWrapper = Wrappers.query();
        queryWrapper.eq(this.columnName, columnValue);
        if(isUpdate) {
            queryWrapper.ne("id", id);
        }
        BaseMapper baseMapper = SpringUtil.getBean(this.mapperClass);
        long count = baseMapper.selectCount(queryWrapper);
        return count==0;
    }
}
